/**
 * 
 */
package com.otrace.actions;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

import com.otrace.exceptions.OTraceGenericException;
import com.otrace.forms.ConnectForm;
import com.otrace.service.ConnectionService;
import com.otrace.service.VirtualMachineService;
import com.otrace.vo.VirtualMachineVO;
import com.sun.jdi.VirtualMachine;

/**
 * @author kvn prabhu
 * 
 */
public class ConnectAction extends Action {
	// Connecting to virtual machine
	VirtualMachine virtualMachine;
	//Virtual Machine Details
	VirtualMachineVO vmVO;

	/**
	 * 
	 */
	/**
	 * Connect Action
	 */
	public ConnectAction() {

	}

	
	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
		HttpSession session = request.getSession(false);
		ConnectForm connectForm = (ConnectForm) form;
		ActionMessages messages = new ActionMessages();
		String output = "";
		String hostName = connectForm.getHostName();
		String port = connectForm.getPort();
		virtualMachine = (VirtualMachine) session.getValue("JVM");
		if (virtualMachine == null) {
			// call service for connection
			try {
				virtualMachine = ConnectionService.connectToJVM(hostName, port);
			} catch (OTraceGenericException ge) {
				output = "inputpage";
				messages.add("connStatus", new ActionMessage(
						"error.notconnected",
						"JVM Not Connected, Please check connection details."));
			}
			if (virtualMachine != null) {
				session.putValue("JVM", virtualMachine);
				connectForm.setConnStatus("Connected");
				connectForm.setConnected(true);
				// Get Virtual Machine details
				vmVO = new VirtualMachineService()
						.fetchJVMDetails(virtualMachine);
				vmVO.setHostName(hostName);
				vmVO.setPort(port);
				request.setAttribute("vmVO", vmVO);

				output = "success";
			} else {
				messages.add("connStatus", new ActionMessage(
						"error.notconnected",
						"JVM Not Connected, Please check connection details."));
				output = "inputpage";
			}
		} else {
			vmVO = new VirtualMachineService().fetchJVMDetails(virtualMachine);
			vmVO.setHostName(hostName);
			vmVO.setPort(port);
			request.setAttribute("vmVO", vmVO);
			output = "success";
		}

		if ("inputpage".equals(output)) {
			return mapping.getInputForward();
		} else {
			return mapping.findForward(output);
		}

	}

}
